<template>
    <div v-if="showPage" class="pa12" style="min-width: 1000px;">
        <el-card style="box-shadow: none;">
            <ul class="flex">
                <li class="flex pa20 border-r" style="min-width: 300px;">
                    <el-image :src="memberDetail.avatar" style="width: 54px;height: 54px;border-radius: 50%;"/>
                    <ul class="f-d-b f-column" style="height: 54px;margin-left: 12px;">
                        <li class="member-info__name">{{ memberDetail.nickname || `用户${memberDetail.mobile}` }}</li>
                        <li v-if="memberDetail.level_name" class="member-info__level f-c">
                            <span class="fz10">{{ memberDetail.level_name }}</span>
                        </li>
                    </ul>
                </li>
                <li style="width: 100%;font-size: 12px;">
                    <div class="f-c border-b" style="height: 50%;">
                        <p class="f-c" style="width: 36%;"><span style="width: 100px;text-align: right;">最后一次访问：</span>{{ memberDetail.last_visit_at || '--' }}</p>
                        <p class="f-c" style="width: 20%;"><span style="width: 80px;text-align: right;">近7天访问：</span>{{ memberDetail.last_7_visit_count || 0 }}次</p>
                        <p class="f-c" style="width: 20%;"><span style="width: 80px;text-align: right;">近30天访问：</span>{{ memberDetail.last_30_visit_count || 0 }}次</p>
                        <p class="f-c" style="width: 24%;"><span style="width: 80px;text-align: right;">近90天访问：</span>{{ memberDetail.last_90_visit_count || 0 }}次</p>
                    </div>
                    <div class="f-c" style="height: 50%;">
                        <p class="f-c" style="width: 36%;"><span style="width: 100px;text-align: right;">最后一次购买：</span>{{ memberDetail.last_buy_at || '--' }}</p>
                        <p class="f-c" style="width: 20%;"><span style="width: 80px;text-align: right;">近7天购买：</span>{{ memberDetail.last_7_buy_count || 0 }}次</p>
                        <p class="f-c" style="width: 20%;"><span style="width: 80px;text-align: right;">近30天购买：</span>{{ memberDetail.last_30_buy_count || 0 }}次</p>
                        <p class="f-c" style="width: 24%;"><span style="width: 80px;text-align: right;">近90天购买：</span>{{ memberDetail.last_90_buy_count || 0 }}次</p>
                    </div>
                </li>
            </ul>
        </el-card>
        <div class="flex" style="margin-top: 12px;">
            <el-card style="width: 250px;box-shadow: none;">

            </el-card>

            <div style="width: calc(100% - 262px);margin-left: 12px;">
                <el-card style="box-shadow: none;">
                    <template #header>会员标签</template>
                    <div style="text-align: center;padding: 20px 0;">暂无数据</div>
                </el-card>

                <g-tabs class="pt12" v-model="tabActive" :list="tabsTable" hide-splicing>
                    <div v-if="!isGroupManagementPage" class="pb10">
                        <el-button v-if="orderActive" type="primary" :icon="Plus" @click="showDialogPayWay">新增消费记录</el-button>
                        <el-button v-if="pointActive" type="primary" :icon="Plus" @click="showDialogPoints">新增积分记录</el-button>
                    </div>
                </g-tabs>

                <div class="border-a radius-b-l-4 radius-b-r-4" style="border-top: 0;">
                    <el-table
                        v-if="orderActive"
                        :data="orderList"
                        v-loading="tableLoading"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column width="150">
                            <template #header>
                                <GTableHeadSelect
                                    name="消费记录来源"
                                    :filters="payOriginFilters"
                                    v-model="tableParams[tabActive].origin"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.origin }}</template>
                        </el-table-column>
                        <el-table-column label="消费金额" width="120" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="row.paid_amount || row.paid_amount === 0">{{ row.paid_amount }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column width="130" show-overflow-tooltip>
                            <template #header>
                                <GTableHeadSelect
                                    name="店铺"
                                    :props="{ value: 'id', label: 'name' }"
                                    :filters="shopFilters"
                                    v-model="tableParams[tabActive].shop_id"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.shop_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column width="120">
                            <template #header>
                                <GTableHeadSelect
                                    name="支付方式"
                                    :filters="payWayFilters"
                                    v-model="tableParams[tabActive].pay_way"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">
                                <div v-if="row.pay_way">
                                    <p v-if="row.origin === '停车缴费'">
                                        <span v-if="+row.pay_type === 2">支付宝</span>
                                        <span v-else>微信</span>
                                    </p>
                                    <span v-else>{{ row.pay_way }}</span>
                                </div>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="微信/支付宝/云闪付交易号" width="200" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.source || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="订单号" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.sn || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="消费时间" width="160" sortable="custom">
                            <template #default="{ row }">{{ row.paid_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="操作人" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.operator || '--' }}</template>
                        </el-table-column>
                    </el-table>

                    <el-table
                        v-if="pointActive"
                        :data="pointList"
                        v-loading="tableLoading"
                        :empty-text="emptyText"
                        @sort-change="tableSortChange"
                        :default-sort="defaultSort"
                        class="table-loading-mask-body"
                    >
                        <el-table-column min-width="130" show-overflow-tooltip>
                            <template #header>
                                <GTableHeadSelect
                                    name="积分变动来源"
                                    inputSearch
                                    :filters="pointsFilters"
                                    v-model="tableParams[tabActive].origin"
                                    @change="mdSearch"
                                />
                            </template>
                            <template #default="{ row }">{{ row.origin || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="积分增加" min-width="120" property="change" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="+row.type === 1">+{{ row.change }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="积分扣除" min-width="120" property="type" sortable="custom">
                            <template #default="{ row }">
                                <span v-if="+row.type === 2 || +row.type === 3">-{{ row.change }}</span>
                                <span v-else>--</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="isUniqueMemberCompany" label="商场" min-width="120" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.mall_name || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="积分创建时间" min-width="160" property="created_at" sortable="custom">
                            <template #default="{ row }">{{ row.created_at || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="操作人" width="150" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.operator || '--' }}</template>
                        </el-table-column>
                        <el-table-column label="备注" min-width="180" show-overflow-tooltip>
                            <template #default="{ row }">{{ row.remark || '--' }}</template>
                        </el-table-column>
                    </el-table>

                    <div class="f-d-c pv15">
                        <GPagination
                            :current-page="tableParams[tabActive].page"
                            :page-size="tableParams[tabActive].per_page"
                            :total="tabsTable[tabActive].count"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <AddPayWay v-model="dialogPayWay" :member-id="memberId"/>

    <AddPoint v-model="dialogPoints" :member-id="memberId"/>
</template>

<script setup lang="ts">
    import { reactive, ref, computed, onMounted } from "vue";
    import { ElMessage } from "element-plus";
    import { Plus } from "@element-plus/icons-vue";
    import { useRoute } from "vue-router";
    import { _mallStore } from "@/store/config";
    import { storeToRefs } from "pinia";
    import useLoading from "@/hooks/loading";

    import AddPayWay from "@/views/MemberManage/MemberList/components/AddPayWay.vue";
    import AddPoint from "@/views/MemberManage/MemberList/components/AddPoint.vue";

    import {
        getRestfulMallMemberDetail,
        getRestfulMallMemberOrders,
        postRestV3CompanyMemberDetail,
        postRestV3OrderList,
        postRestV3PointList,
        getRestfulMallMemberPoints,
    } from "@/assets/api";
    import { getApiMajorListFilter, getRestfulPointsFiltersHandler } from "@/assets/api/handler";
    import { getTableSortOrder, handlerOperator, TypeSortParams, TypeTableSort } from "@/utils/handlerData";
    import { FPayOriginFilters, FPayWayFilters } from "@/filters";
    import { TypeFilters } from "@/interface/filters";

    const { isUniqueMemberCompany, isGroupManagementPage } = storeToRefs(_mallStore);
    const { showLoading, hideLoading } = useLoading();
    const route = useRoute();
    const memberId: number = +route.params.id;

    let zeusConfigTicket = ref<ObjValueAny>({});
    let showPage = ref<boolean>(false);
    onMounted(() => {
        getShopList();
        getPointsFilters();
        showLoading();
        getMemberDetail();
        getOrderList();
        getPointData();
    })
    // 会员详情 ===========================================================================
    let memberDetail = ref<ObjValueAny>({});
    const getMemberDetail = (): Promise<void> => {
        return new Promise(async resolve => {
            let resp: ObjValueAny;
            if (isGroupManagementPage.value) {
                resp = await postRestV3CompanyMemberDetail({
                    mall_id: _mallStore.mallId,
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                });
            } else {
                resp = await getRestfulMallMemberDetail(memberId);
            }
            if (resp.code === 200) {
                const { data } = resp;
                if (data.real_name) {
                    data.real_name = realNameHandler(data.real_name);
                }
                memberDetail.value = data;
            } else {
                ElMessage.error(resp.msg);
            }
            hideLoading();
            showPage.value = true;
            resolve();
        })
    }
    const realNameHandler = (name: string) => {
        let _nameLength = name.length;
        if (_nameLength > 2) {
            return `${name.slice(0, 1)}${'*'.repeat(_nameLength - 2)}${name.slice(-1)}`;
        } else if (_nameLength === 2) {
            return `*${name.slice(-1)}`;
        }
        return name;
    }

    // 表格table切换
    const tabActive = ref<number>(0);
    const tabsTable = reactive<ObjValueAny>([
        { value: 0, label: '消费记录', count: 0 },
        { value: 1, label: '积分记录', count: 0 },
        { value: 2, label: '优惠券记录', count: 0 },
        { value: 3, label: '会员信息变动记录', count: 0 },
    ]);
    const commonParams: ObjValueAny = { page: 1, per_page: 10, order_by: '', sort: '' };
    const tableParams = reactive<{ [props: string]: ObjValueAny }>({
        // 消费记录
        0: { ...commonParams, origin: '', pay_cate: 'cash', pay_way: '', without_statuses: [16, 18], shop_id: '' },
        // 积分记录
        1: { ...commonParams, change: 2, origin: '', pay_cate: 'cash' },
        // 优惠券记录
        2: { ...commonParams, group_id: -1, soule: '', status: '' },
        // 会员信息变动记录
        3: { ...commonParams, member_id: memberId, mall_id: _mallStore.mallId, company_id: _mallStore.companyId, action: '' },
    })

    // 消费记录 ===========================================================================
    const orderActive = computed(() => {
        return tabActive.value === 0;
    })
    // 积分记录 ===========================================================================
    const pointActive = computed(() => {
        return tabActive.value === 1;
    })
    // 优惠券记录 ===========================================================================
    const couponActive = computed(() => {
        return tabActive.value === 2;
    })
    // 会员信息变动记录 ===========================================================================
    const memberActive = computed(() => {
        return tabActive.value === 3;
    })

    const mdSearch = () => {
        handleCurrentChange();
    }
    // 排序
    const defaultSort = ref<TypeTableSort>({ prop: '', order: '' });
    const tableSortChange = ({ order, prop }: TypeTableSort) => {
        const paramsSort: TypeSortParams = getTableSortOrder(order, prop);
        tableParams[tabActive.value] = Object.assign(tableParams[tabActive.value], paramsSort);
        mdSearch();
    }
    // 选择 每页条数
    const handleSizeChange = (count: number) => {
        tableParams[tabActive.value].per_page = count;
        mdSearch();
    }
    // 分页
    const handleCurrentChange = (page: number = 1) => {
        tableParams[tabActive.value].page = page;
        getTableList();
    }

    let emptyText = ref<string>('');
    let tableLoading = ref<boolean>(false);
    const getTableList = async () => {
        // 消费记录
        if (orderActive.value) {
            await getOrderList();
        }
        // 积分记录
        if (pointActive.value) {
            await getPointData();
        }
        // 优惠券记录
        if (couponActive.value) {

        }
        // 会员信息变动记录
        if (memberActive.value) {

        }
    }
    const showTableEmpty = () => {
        emptyText.value = '加载中...';
        tableLoading.value = true;
    }
    const hideTableEmpty = () => {
        emptyText.value = '暂无数据';
        tableLoading.value = false;
    }
    // 消费记录 ==============================================================================
    const payOriginFilters = reactive<TypeFilters.filter[]>(FPayOriginFilters);
    const payWayFilters = reactive<TypeFilters.filter[]>(FPayWayFilters);
    const orderList = ref<ObjValueAny[]>([]);
    const getOrderList = (): Promise<void> => {
        return new Promise(async resolve => {
            showTableEmpty();
            let resp: ObjValueAny;
            if (_mallStore.isUniqueMemberCompany) {
                resp = await postRestV3OrderList({
                    ...tableParams[0],
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                    types: [1, 3, 4, 5, 6, 7, 8, 9, 11],
                }, { noRepeat: 1 });
            } else {
                resp = await getRestfulMallMemberOrders(memberId, tableParams[0], { noRepeat: 1 });
            }
            if (resp.code === 200) {
                const { data } = resp;
                for (let row of data) {
                    row.operator = handlerOperator(row.operator);
                    row.source = +row.type === 1 ? row.transaction_source : row.transaction_id;
                    if (+_mallStore.mallId === +row.shop_id) {
                        row.shop_name = '商场';
                    }
                }
                orderList.value = data;
                tabsTable[0].count = resp.meta?.total;
            } else {
                ElMessage.error(resp.msg);
            }
            hideTableEmpty();
            resolve();
        })
    }

    // 积分记录 ==============================================================================
    const pointList = ref<ObjValueAny[]>([]);
    const getPointData = (): Promise<void> => {
        return new Promise(async resolve => {
            showTableEmpty();
            let resp: ObjValueAny;
            if (isGroupManagementPage.value) {
                resp = await postRestV3PointList({
                    ...tableParams[1],
                    company_id: _mallStore.companyId,
                    member_id: memberId,
                }, { noRepeat: 2 });
            } else {
                resp = await getRestfulMallMemberPoints(memberId, tableParams[1], { noRepeat: 2 });
            }
            if (resp.code === 200) {
                const { data } = resp;
                for (let row of data) {
                    row.operator = handlerOperator(row.operator);
                    if (row.mall && row.mall.name) {
                        row.mall_name = row.mall.name;
                    }
                }
                pointList.value = data;
                tabsTable[1].count = resp.meta?.total;
            } else {
                ElMessage.error(resp.msg);
            }
            hideTableEmpty();
            resolve();
        })
    }

    // 新增 消费记录/积分记录 ===========================================================================
    let addNewType = ref<string>('');
    let dialogPayWay = ref<boolean>(false);
    let dialogPoints = ref<boolean>(false);
    // 新增消费记录
    const showDialogPayWay = () => {
        addNewType.value = 'payWay';
        dialogPayWay.value = true;
    }
    // 新增积分记录
    const showDialogPoints = () => {
        addNewType.value = 'point';
        dialogPoints.value = true;
    }

    // 店铺 筛选
    const shopFilters = ref<ObjValueAny[]>([]);
    const getShopList = async () => {
        shopFilters.value = await getApiMajorListFilter();
    }
    // 积分变动来源 筛选
    const pointsFilters = ref<ObjValueAny[]>([]);
    const getPointsFilters = async () => {
        pointsFilters.value = await getRestfulPointsFiltersHandler();
    }
    // 优惠券记录 =================================================================================
    const getCouponRecord = () => {

    }
    // 会员信息变动记录 ===========================================================================
    const getMemberChangeLog = () => {

    }
</script>

<style scoped lang="scss">
    :deep(.el-card__body) {
        padding: 0;
    }

    .member-info__name {
        color: $highlight-color;
        font-size: 18px;
        font-weight: 600;
    }

    .member-info__level {
        width: fit-content;
        padding: 0 12px;
        color: $highlight-color;
        border: 1px solid;
        border-radius: 10px;
        line-height: 20px;
    }
</style>